package com.mzmarket.market.console.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mzmarket.market.console.domain.ValueInfo;
import com.mzmarket.market.module.entity.User;
import com.mzmarket.market.module.service.UserService;
import com.mzmarket.market.module.utils.JwtCookieUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Base64;
import java.util.Date;

@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取所有 cookie
        Cookie[] cookies = request.getCookies();

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) { // 假设你的 cookie 名称是 token
                    String cookieValue = cookie.getValue();
                    //将cookieValue解码
                    ObjectMapper objectMapper = new ObjectMapper();
                    ValueInfo valueInfo = objectMapper.readValue(Base64.getDecoder().decode(cookieValue),
                            ValueInfo.class);
                    if (isValid(valueInfo.getToken())) { // 校验逻辑
                        return true; // 校验通过，继续执行 Controller
                    }
                }
            }
        }

        // 校验失败，返回 401 或自定义信息
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("Unauthorized: Invalid cookie");
        return false; // 拦截请求，不执行 Controller
    }

    // 校验方法，根据你的业务逻辑
    private boolean isValid(String token) {

        // 这里可以校验 JWT 签名、过期时间，或者去数据库查 session
        Claims claims = JwtCookieUtil.decrypt(token);
        String phone = claims.getSubject();

        User user = null;
        try {
            user = userService.getByPhone(phone);//确认存入用户信息是否准确
        } catch (Exception e) {
            return false;
        }
        if (user == null) {
            return false;
        } else {
            Date expireDate = claims.getExpiration();//确认token是否过期
            int result = new Date(System.currentTimeMillis()).compareTo(expireDate);
            return result <= 0;
        }

    }
}

